//
//  HomeViewController.swift
//  FM
//
//  Created by x on 2017/8/23.
//  Copyright © 2017年 HLB. All rights reserved.
//

import UIKit

class HomeViewController: UIViewController {

    /// 用来保存tableView
    weak var weakTableView:UITableView?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
    }
    
    /// 初始化
    private func setupUI() -> Void {
        //1.设置导航栏的属性
        view.backgroundColor = UIColor.white
        navigationItem.title = "首页"
        
        //1.1添加子控件
        view.addSubview(homeTableView)
        
        //2.加载首页数据
        NetWorTools.shareNetWorkTools().loadHomeData(successCallBack: { (data) in
            self.dataSource = data
            self.weakTableView?.reloadData()
        }) { (error) in
            print("loadHomeData=======\(error)")
        }
    }
        
    /// 设置到状态栏的颜色
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return UIStatusBarStyle.lightContent
    }
    
    //MARK -- 懒加载
    
    fileprivate lazy var recommedView:RecommendView = {
        let tt = RecommendView(frame: CGRect.init(x: 0, y:0, width: self.view.bounds.width, height: 150))
        tt.delegate = self
        
        return tt
    }()
    
    fileprivate lazy var categoryView:CategoryView = {
        let tt = CategoryView(frame: CGRect.init(x: 0, y: 150, width: self.view.bounds.width, height: 120))
        tt.categoryDelegate = self
        
        return tt
    }()
    
    private lazy var homeTableView:UITableView = {
        let tableView = UITableView()
        tableView.frame = CGRect.init(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height-64)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = UITableViewCellSeparatorStyle.none
        //注册cell
        tableView.register(HomeRecommendTableViewCell.self, forCellReuseIdentifier: HomeRecommendIdentifier)
        tableView.register(HomeFMTableViewCell.self, forCellReuseIdentifier: HomeFMCellIdentifier)
        tableView.register(HomeRadioTableViewCell.self, forCellReuseIdentifier: HomeRadioCellIdentifier)
        //注册表格头视图
        tableView.register(HomeTableHeadView.self, forHeaderFooterViewReuseIdentifier: HomeHeadViewreuseIdentifier)

        self.weakTableView = tableView
    
        return tableView
    }()
    
    /// 表格数据源
    fileprivate lazy var dataSource:[AnyObject] = [AnyObject]()
    
    /// 缓存表格行高的字典
    fileprivate lazy var rowHeightCaches:[String:CGFloat] = [String:CGFloat]()
}

/// cell的标记
private let HomeRecommendIdentifier = "HomeRecommendIdentifier"

/// FMcell的标记
private let HomeFMCellIdentifier = "HomeFMCellIdentifier"

/// 电台cell的标记
private let HomeRadioCellIdentifier = "HomeRadioCellIdentifier"

/// 表格头视图的标记
private let HomeHeadViewreuseIdentifier = "HomeHeadViewreuseIdentifier"

extension HomeViewController:UITableViewDelegate,UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.dataSource.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case 2,5:
            return (dataSource.count == 0) ? 0 : 1
        case 3,4:
            guard dataSource.count == 0 else {
                let models = dataSource[section] as! [HomeFM]
                return models.count
            }
            return 0
        default:
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section == 3 || indexPath.section == 4{
            let cell = tableView.dequeueReusableCell(withIdentifier: HomeFMCellIdentifier) as! HomeFMTableViewCell
            let models = dataSource[indexPath.section] as! [HomeFM]
            cell.model = models[indexPath.row]
            return cell
        }else if indexPath.section == 5{
            let cell = tableView.dequeueReusableCell(withIdentifier: HomeRadioCellIdentifier) as! HomeRadioTableViewCell
            let models = dataSource[indexPath.section] as! [Radio]
            cell.delegate = self;
            cell.radios = models
            
            return cell
        }else {
            let cell = tableView.dequeueReusableCell(withIdentifier: HomeRecommendIdentifier) as! HomeRecommendTableViewCell
            let models = dataSource[indexPath.section] as! [HomeFM]
            cell.delegate = self
            cell.models = models
            return cell
        }
    }
    
    
    //cell的点击方法
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        //取消cell的点击效果
        tableView.deselectRow(at: indexPath, animated: true)
        if indexPath.section == 3 || indexPath.section == 4 {
            
            //1.添加转场动画
            AnimationTools.addAnimationToKeyWindow(animationType: "rippleEffect")
            
            //2.跳转VC
            let totalFM = dataSource[indexPath.section] as! [HomeFM]
            let playerController = HomePlayerViewController(data: totalFM, index: indexPath.row)
            playerController.hidesBottomBarWhenPushed = true
            navigationController?.pushViewController(playerController, animated: true)
        }
    }
    
    //计算cell的行高
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 || indexPath.section == 1 {
            return 0
        }else if indexPath.section == 2 {
            return 80
        }else if indexPath.section == 5{
            return (view.bounds.width-40)/4 + 20
        }else {
            let models = dataSource[indexPath.section] as! [HomeFM]
            let model = models[indexPath.row]
            
            //1.首先冲缓存中取出行高
            if rowHeightCaches[model.id!] != nil {
                return rowHeightCaches[model.id!]!
            }
            
            //2.如果缓存中没有,则重新计算行高
            //2.1拿到cell
            let cell = tableView.dequeueReusableCell(withIdentifier: HomeFMCellIdentifier) as! HomeFMTableViewCell
            
            let rowHeight = cell.rowHeigh(model: model)
            //把计算得到的行高,缓存到内存中
            rowHeightCaches[model.id!] = rowHeight
            
            return rowHeight
        }
    }
    
    //返每个分去的头视图
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        switch section {
        case 0:
            //传递一个url数组
            let recomoments = (self.dataSource[section]) as! [RecomomendModel]
            var urls:[URL] = [URL]()
            for model in recomoments {
                if model.coverImageURL != nil {
                    urls.append(model.coverImageURL!)
                }
            }
            recommedView.models = urls
            return recommedView
            
        case 1:
            categoryView.models = (self.dataSource[section]) as? [CategoryModel]
            return categoryView
            
        default:
            let headView = tableView.dequeueReusableHeaderFooterView(withIdentifier: HomeHeadViewreuseIdentifier) as! HomeTableHeadView
            headView.delegate = self
            headView.cellIndex = section
            return headView
        }
    }
    
    //返回头视图的高度
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        switch section {
        case 0:
            return recommedView.frame.height
            
        case 1:
            return categoryView.frame.height
        default:
            return 30
        }
    }
}

//MARK:-- <RecommendViewDelegate,HomeRecommendTableViewCellDelegate,CategoryViewDelegate>
extension HomeViewController:RecommendViewDelegate,CategoryViewDelegate,HomeRecommendTableViewCellDelegate,HomeRadioTableViewCellDelegate,HomeTableHeadViewDelegate {
    
    func btuWillClick(index: Int) {
        let recomoments = (self.dataSource[0]) as! [RecomomendModel]
        let model = recomoments[index]
        guard model.jumpURL != nil else {
            return
        }
        let WebVc = WebViewViewController(url: model.jumpURL!)
        WebVc.hidesBottomBarWhenPushed = true
        navigationController?.pushViewController(WebVc, animated: true)
    }
    
    func categoryBtuClick(categotyID: String, btuTitle:String) {
        let  categoryController = CategoryViewController()
        categoryController.categoryID = categotyID
        categoryController.naviTitle = btuTitle
        categoryController.hidesBottomBarWhenPushed = true
        navigationController?.pushViewController(categoryController, animated: true)
    }
    
    func homeRecommendTableViewCellplayFM(currentIndex: Int, totalFM: [HomeFM]) {
        
        //1.添加转场动画
        AnimationTools.addAnimationToKeyWindow(animationType: "rippleEffect")
        
        //2.跳转VC
        let playerController = HomePlayerViewController(data: totalFM, index: currentIndex)
        playerController.hidesBottomBarWhenPushed = true
        navigationController?.pushViewController(playerController, animated: true)
    }
    
    func radioDetailsButtonWillClick(radio: Radio) {
        //1.跳转界面加载详情
        let radioDetailsController = RadioDetailsViewController()
        radioDetailsController.currentRadio = radio
        radioDetailsController.hidesBottomBarWhenPushed = true
        navigationController?.pushViewController(radioDetailsController, animated: true)
    }
    
    func moreBtuDidClick(currentIndex: Int) {
        switch currentIndex {
        case 3,4:
            print("最新fm...")
            //1.跳转界面加载更多FM
//            let newFmVC = NewFMViewController()
//            if currentIndex == 3 {
//                newFmVC.is_teacher = 0
//            }else {
//                newFmVC.is_teacher = 1
//            }
//            newFmVC.hidesBottomBarWhenPushed = true
//            navigationController?.pushViewController(newFmVC, animated: true)
            
        case 5:
            print("最新电台...")
            let moreRadioController = MoreRadioViewController()
            moreRadioController.hidesBottomBarWhenPushed = true
            navigationController?.pushViewController(moreRadioController, animated: true)
            
        default:
            break
        }
    }
}









